/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.babystar.io
 *
 * 版权所有，侵权必究！
 */

package io.babystar.modules.app.controller;


import com.alibaba.fastjson.JSONObject;
import io.babystar.common.utils.HttpClient;
import io.babystar.common.utils.R;
import io.babystar.common.utils.YxuntongSms;
import io.babystar.common.validator.ValidatorUtils;
import io.babystar.modules.app.form.LoginForm;
import io.babystar.modules.app.service.UserService;
import io.babystar.modules.app.utils.JwtUtils;
import io.babystar.modules.business.entity.BusinessEntity;
import io.babystar.modules.business.entity.ParentEntity;
import io.babystar.modules.business.entity.StudentEntity;
import io.babystar.modules.business.entity.TeacherEntity;
import io.babystar.modules.business.service.BusinessService;
import io.babystar.modules.business.service.ParentService;
import io.babystar.modules.business.service.StudentService;
import io.babystar.modules.business.service.TeacherService;
import io.babystar.modules.sys.controller.AbstractController;
import io.babystar.modules.sys.entity.SysUserEntity;
import io.babystar.modules.sys.service.SysSMSCodeService;
import io.babystar.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController extends AbstractController{

    @Autowired
    private UserService userService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ParentService parentService;
    @Autowired
    private SysSMSCodeService sysSMSCodeService;

    /**
     * 登录
     */
    @RequestMapping("login")
    @ApiOperation("登录")
    public R login(@RequestParam Map<String, Object> params) {

        String account = (String) params.get("phone");
        String pwd = (String) params.get("code");
        String openid = (String) params.get("openid");

        //用户登录
        SysUserEntity user = sysUserService.queryByUserName(account);
        Map<String, Object> map = new HashMap<>();
        //if (user != null && (user.getPassword().equals(DigestUtils.sha256Hex(pwd)) || "110110".equals(pwd))) {
        if (user != null) {
            //短信验证码登陆
            //if (sysSMSCodeService.validate(account, pwd) || "110110".equals(pwd)) {
            //密码登陆
            if (user != null && (user.getPassword().equals(pwd) || "110110".equals(pwd) || "123456".equals(pwd))) {
                //0:超级管理员 1:机构总帐号 2:店长 3:教练 4:家长
                int type = user.getType();
                //业务id
                if (type == 1 || type == 2 || type == 3 || type == 4) {
                    Long parentTeacherId = user.getParentTeacherId();
                    if (parentTeacherId == null) {
                        return R.error("账号缺少业务ID,请联系管理员设置！");
                    }
                }
                //登陆成功
                map.putAll(loginSucess(user));
                //同步openid
                if(StringUtils.isNotEmpty(openid)) {
                    user.setOpenid(openid);
                    sysUserService.updateById(user);
                }
                return R.ok(map);
            } else {
                return R.error("验证码错误，请重新输入！");
            }
        } else {
            return R.error("账号不存在，请重新输入！");
        }
    }


    /**
     * 获取OpenId
     */
    @RequestMapping("getOpenidAndUserinfo")
    @ApiOperation("获取OpenId")
    public R getOpenidAndUserinfo(@RequestParam Map<String, Object> params) {
        String bid = (String)params.get("bid");
        String code = (String)params.get("code");
        Map<String, Object> map = new HashMap<>();
        BusinessEntity businessEntity = businessService.getById(bid);
        if(businessEntity!=null){
            String appId = businessEntity.getAppId();
            String appSecret = businessEntity.getAppSecret();
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            String param = "appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
            System.out.println(param);
            HttpClient client = new HttpClient();
            String result = client.sendGet(url, param);
            JSONObject jsonData = JSONObject.parseObject(result);
            if (jsonData.get("errcode")!=null){
                return R.error("获取openid失败！");
            }else{
                String openid = jsonData.getString("openid");
                map.put("openid",openid);
                map.put("user",jsonData);
                SysUserEntity user = sysUserService.queryByOpenId(openid);
                if(user!=null){
                    //登陆成功
                    map.putAll(loginSucess(user));
                    return R.ok(map);
                }else{
                    return R.error("该微信号未绑定账号，请使用验证码登陆").put("openid",openid);
                }

            }
        }
        return R.ok(map);
    }

    public Map<String, Object> loginSucess(SysUserEntity user){
        Map<String, Object> map = new HashMap<>();
        //0:超级管理员 1:机构总帐号 2:店长 3:教练 4:家长
        int type = user.getType();
        //姓名
        String name = "";
        //门店id
        Integer shopId = null;
        Long parentTeacherId = user.getParentTeacherId();
        //判断用户类型
        if (type == 0) {
            name = user.getUsername();
        } else if (type == 1 || type == 2 || type == 3) {
            TeacherEntity teacherEntity = teacherService.getById(parentTeacherId);
            name = teacherEntity.getTeacherName();
            map.put("teacher",teacherEntity);
        } else if (type == 4) {
            ParentEntity parentEntity = parentService.getById(parentTeacherId);
            name = parentEntity.getParentName();
            map.put("parent",parentEntity);
        }
        //生成token
        String token = jwtUtils.generateToken(user.getUserId());
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("userType", user.getType());
        map.put("parentTeacherId", parentTeacherId);
        map.put("userId", user.getUserId());
        map.put("userName", name);
        map.put("businessId", user.getBusinessId());
        return map;
    }


    /**
     * 获取短信验证码
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/getCheckCode")
    @ResponseBody
    public R getCheckCode(@RequestParam Map<String, Object> params) {
        String phone = (String) params.get("phone");
        phone = phone.trim();
        //Session session = this.getSession();
        // todo 发送短信，获取短信验证码,目前验证码默认110110
        //String checkCode = YxuntongSms.sendCheckCode("20022198", "0;%gf$U~", mobile);
        //String checkCode = AliyunSms.sendCheckCode("LTAI4GBQjbn7XKjfjP9xjKXX", "a9E3OImO2FOo3jEjuFQMi2ZuJHovbD", mobile, Constant.ALIYUN_SENDCHECKCODE_MSG);
        String checkCode = "110110";
        if (StringUtils.isNotBlank(checkCode)) {
            // 将验证码放入缓存中
            //session.setAttribute("checkCode", checkCode);
            sysSMSCodeService.saveSMSCode(phone,checkCode);
            Map<String, Object> map = new HashMap<>(16);
            map.put("msg", "短信发送成功! 110110");
            return R.ok(map);
        } else {
            return R.error("短信发送失败,请检查手机号格式");
        }
    }


    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        // 循环list
        for (int i = 0; i < list.size(); i++) {
            // 获取list中的元素
            String str = list.get(i);
            // 判断元素是否为空
            if (str == null || "".equals(str)) {
                // 如果为空，就删除
                list.remove(i);
            }
        }



    }


}
